package com.tkmybatis.config;

import com.alibaba.druid.pool.DruidDataSource;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import tk.mybatis.spring.annotation.MapperScan;

import javax.sql.DataSource;
import java.sql.SQLException;

@Slf4j
@Configuration
@EnableConfigurationProperties({SlaveDruidDataSourceProperties.class})
@MapperScan(basePackages = {"com.tkmybatis.posrtgre.mapper"}, sqlSessionFactoryRef = "msgSqlSessionFactory")
public class SlaveDruidConfig {
    @Autowired
    private SlaveDruidDataSourceProperties properties;

    @Bean("msgDataSource")
    public DataSource msgDataSource() {
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName(properties.getDriverClassName());
        druidDataSource.setUrl(properties.getUrl());
        druidDataSource.setUsername(properties.getUsername());
        druidDataSource.setPassword(properties.getPassword());
        try {
            druidDataSource.setFilters(properties.getFilters());
            druidDataSource.init();
        } catch (SQLException e) {
            log.error("error:",e);
        }

        return druidDataSource;
    }
    
    // 创建该数据源的事务管理
    @Bean(name = "msgTransactionManager")
    public DataSourceTransactionManager msgTransactionManager() throws SQLException {
        return new DataSourceTransactionManager(msgDataSource());
    }

    // 创建Mybatis的连接会话工厂实例
    @Bean(name = "msgSqlSessionFactory")
    public SqlSessionFactory msgSqlSessionFactory(@Qualifier("msgDataSource") DataSource msgDataSource) throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(msgDataSource);  // 设置数据源bean
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath*:mapper/postgre/*.xml"));  // 设置mapper文件路径
        return sessionFactory.getObject();
    }
    
    @Bean
	public SqlSessionTemplate msgSqlSessionTemplate(
			@Qualifier("msgSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
		SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory); // 使用上面配置的Factory
		return template;
	}

}
